#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#define BUFFER_SIZE 1024

char buf[BUFFER_SIZE];
typedef struct End{
    char *buf;
    int len;
}End;
pthread_t out, in;

void *out_thread(void *arg) {
    while (1) {
        // 将缓冲区中的数据写入标准输出
        write(STDOUT_FILENO, buf, strlen(buf));
        if (buf[0] == 'q' && buf[1] == '\n')
        {
            /* code */
            End *end=malloc(sizeof(End));
            end->buf = "bye";
            end->len = 3;
            pthread_cancel(in);
            pthread_exit((void *)end);
            
        }
        memset(buf, 0, BUFFER_SIZE);

        // 休眠1秒

        sleep(1);
    }
    return NULL;
}

void *in_thread(void *arg) {
    while (1) {
        // 从标准输入读取数据到缓冲区
        read(STDIN_FILENO, buf, BUFFER_SIZE);
    }
    return NULL;
}

int main(int argc, char const *argv[]) {
    

    // 创建输入线程
    pthread_create(&in, NULL, in_thread, NULL);
    // 创建输出线程
    pthread_create(&out, NULL, out_thread, NULL);
    End *end=NULL;
    // 等待输出线程结束
    pthread_join(out, (void **)&end);
    printf("%s\n", end->buf);
    pthread_join(in, NULL);
    
    return 0;
}
